//
//  PlayerManager.m
//  片刻
//
//  Created by lanou3g on 15/6/10.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "PlayerManager.h"

@implementation PlayerManager
-(instancetype)init
{
    self = [super init];
    if (self) {
        self.avPlayer = [[AVPlayer alloc] init]; //播放器初始化
        self.avPlayerItme = [[AVPlayerItem alloc] init]; //播放器初始化
        _playerArr = [[NSArray alloc]init]; //数组初始化
        _playerIndex = 0;
    }
    return self;
}
-(void)setPlayerArr:(NSArray *)playerArr
{
    if (_playerArr != playerArr) {
        [_playerArr release];
        _playerArr = [playerArr retain];
//        设置数组的适合初始化一个播放器内容
        _avPlayerItme = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:_playerArr[_playerIndex]]];
//        给播放器设置准备播放的内容
        [_avPlayer replaceCurrentItemWithPlayerItem:_avPlayerItme];
    }
}
-(playerState)playerState{
    if (_avPlayer.rate == 0) {
        return playerStatePaue;
    }
    return playerStatePlay;
}


//播放
-(void)play
{
    [_avPlayer play]; //系统方法 播放
}
//暂停
-(void)pause
{
    [_avPlayer pause]; //系统方法  停止
}
//下一首
-(void)downMusic
{
//   先判定模式  如果是随机
    if (_playerModel == playerModelRandom) {
        _playerIndex = arc4random()%self.playerArr.count;
    }else{
        _playerIndex++;
    }
//    在判断第几首
    if (_playerIndex >= _playerArr.count - 1) {
        _playerIndex = 0;
    }
    [self cehangMusicWithIndex:_playerIndex];
}
//上一首
-(void)upMusic
{
    if (_playerModel == playerModelRandom) {
        _playerIndex = arc4random()%self.playerArr.count;
    }
    else{
        _playerIndex--;
    }
    if (_playerIndex < 0 ) {
        _playerIndex = self.playerArr.count-1;
    }
    [self cehangMusicWithIndex:_playerIndex];
}
//根据下标来切换音乐
-(void)cehangMusicWithIndex:(NSInteger)index{
    _playerIndex = index;
//     注意要用self 不然会内存泄露
    self.avPlayerItme = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:_playerArr[index]]];
    [self.avPlayer replaceCurrentItemWithPlayerItem:_avPlayerItme];
}
+(instancetype)sharedManager
{
    static PlayerManager *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[PlayerManager alloc] init]; // 初始化这个类
    });
    return player;
}

@end
